package com.saycode.back.article.service.impl;


import com.saycode.back.article.service.ArticleService;
import com.saycode.common.Constant;
import com.saycode.common.MethodUtil;
import com.saycode.common.beans.Article;
import com.saycode.common.beans.ArticleContent;
import com.saycode.common.beans.User;
import com.saycode.common.dao.ArticleContentRepository;
import com.saycode.common.dao.ArticleRepository;
import com.saycode.common.enums.StatusEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhangyanhui on 2017/6/14.
 */
@Service("back/articleService")
@RequestMapping("back/articleService")
public class ArticleServiceImpl implements ArticleService {
    @Autowired
    private ArticleRepository articleRepository;
    @Autowired
    private ArticleContentRepository articleContentRepository;

    @Override
    public Page<Article> findByUserId(Long userId, int pageNum) {
        PageRequest request = new PageRequest(pageNum-1, Constant.PAGE_NUM,new Sort(Sort.Direction.DESC,"createDate"));
        return articleRepository.findByUserId(userId, request);
    }
    public void save(Article article,String content){
        article.setStatus(StatusEnum.no_published.getKey());
        article.setUpdateDate(article.getCreateDate());
        ArticleContent articleContent = new ArticleContent();
        articleContent.setId(article.getId());
        articleContent.setContent(content);
        articleRepository.save(article);
        articleContentRepository.save(articleContent);
    }
    public Article findById(Long id){
        return articleRepository.findById(id);
    }
    public void save(Article article){
        article.setUpdateDate(new Date());
        articleRepository.save(article);
    }

    @Override
    public ArticleContent findContentById(Long id) {
        return articleContentRepository.findById(id);
    }

    @Override
    public void delete(Long id) {
        articleRepository.delete(id);
        articleContentRepository.delete(id);
    }
}
